from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from django.core.paginator import Paginator
from myapp.Ser import TeacherModelSerializer, StudentModelSerializer
from myapp.models import Teacher, Student


class TeacherAPI(APIView):
    def get(self, request):
        id = request.GET.get('id')
        if id:
            data = Teacher.objects.all()
            data1 = TeacherModelSerializer(data, many=True)
            return Response(data1.data)
        else:
            data = Teacher.objects.all()
            data = TeacherModelSerializer(data, many=True)
            return Response(data.data)

    def post(self, request):
        data = TeacherModelSerializer(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'meg': '添加成功'})
        else:
            return Response({'meg': '添加失败'})


class StudentAPI(APIView):
    def get(self, request):
        id = request.GET.get('id')
        pid = request.GET.get('pid')
        fid = request.GET.get('fid')
        if id:
            data = Student.objects.all()
            page1 = Paginator(data,1)
            page2 = page1.page(pid)
            data1 = StudentModelSerializer(page2,many=True)
            return Response({
                'data':data1.data,
                'page_range':[i for i in page1.page_range]
            })
        else:
            data = Student.objects.get(pk=fid)
            data.num += 1
            data.save()
            data = StudentModelSerializer(data)
            return Response(data.data)

    def post(self, request):
        data = StudentModelSerializer(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'meg': '添加成功'})
        else:
            return Response({'meg': '添加失败'})

    def put(self, request):
        id = request.GET.get('id')
        data = Student.objects.get(pk=id)
        data1 = StudentModelSerializer(instance=data, data=request.data, partial=True)
        if data1.is_valid():
            data1.save()
            return Response({'meg': '转移成功'})
        else:
            return Response({'meg': '转移失败'})


class Seek(APIView):
    def get(self,request):
        id = request.GET.get('id')
        data = Student.objects.filter(name__contains=id)
        data1 = StudentModelSerializer(data,many=True)
        return Response(data1.data)